const svgCaptcha = require("svg-captcha");
const crypto = require("crypto");
const redisClient = require("../utils/redisClient");

class CaptchaImageService {
  constructor() {
    this.generateMixedCodeApi = this.generateMixedCodeApiSvg.bind(this);
  }

  async generateMixedCodeApiSvg(req, res) {
    try {
      const captcha = svgCaptcha.create({
        size: 4, // 验证码长度
        ignoreChars: "o01il", // 忽略字符
        color: true, // 背景色
        noise: Math.floor(Math.random() * 5), // 干扰线条
        width: 116, // 图片宽
        height: 40, //图片长
      }); // 生成验证码 { text: '验证码', data: 'svg图片' }
      // 生成验证码
      const code = captcha.text;
      const uuid = crypto.randomUUID();

      // 将验证码存入Redis，设置5分钟过期时间
      const captchaKey = `captcha:${uuid}`;
      await redisClient.set(captchaKey, code, 300); // 300秒 = 5分钟
      return res.status(200).send({
        code: 200,
        msg: "验证码生成成功",
        img: captcha.data,
        uuid: uuid,
      });
    } catch (error) {
      return res.status(500).send({
        code: 500,
        msg: "生成验证码失败",
        error: error.message,
      });
    }
  }
}

// 创建实例
const captchaImageService = new CaptchaImageService();

// 导出服务实例的方法
module.exports = {
  generateMixedCode: captchaImageService.generateMixedCodeApiSvg,
};
